<template>
  <section class="course-tasks">
    <!-- 头部 -->
    <div class="header">
      <!-- 当前要查看的课程名称 -->
      <el-page-header
        :content="contentPageTitle"
        @back="
          () => {
            this.$router.back();
          }
        "
      >
      </el-page-header>
      <!-- 添加章节的按钮 -->
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleShowAddSection"
        >添加章节</el-button
      >
    </div>
    <!-- 树形控件，来展示课程对应的章节信息 -->
    <el-tree
      :data="sections"
      :props="treeProps"
      v-loading="loading"
      element-loading-text="正在处理中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div class="inner" slot-scope="{ data, node }">
        <span>{{ data.section_name || data.theme }}</span>
        <span class="actions">
          <!-- 编辑章节  @click.stop 阻止事件冒泡 -->
          <el-button
            size="small"
            v-if="node.level === 1"
            @click.stop="handleEditSection(data)"
            >编辑</el-button
          >
          <!-- 修改章节状态 已隐藏、待更新、已更新-->
          <el-button
            size="small"
            v-if="node.level === 1"
            @click.stop="showStatus(data)" v-text="statusMapping[data.status]"></el-button>
        </span>
      </div>
    </el-tree>
    <!-- 修改章节的状态 -->
    <el-dialog
      class="toggle-dialog"
      title="修改章节状态"
      :visible.sync="showStatusForm"
      width="30%"
    >
      <header class="toggle-header">
        <i class="el-icon-info"></i>
        <span>
          当前状态：{{
            statusForm.data && statusMapping[statusForm.data.status]
          }}
        </span>
      </header>
      <el-form label-position="right" label-width="110px" :model="statusForm">
        <el-form-item label="状态变更为：">
          <el-select v-model="statusForm.status" style="width: 100%">
            <el-option
              v-for="(item, index) in Object.keys(statusMapping)"
              :key="index"
              :label="statusMapping[item]"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showStatusForm = false">取 消</el-button>
        <el-button type="primary" @click="updateStatus">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加修改章节 -->
    <el-dialog
      class="add-dialog"
      title="章节信息"
      :visible.sync="showAddSection"
    >
      <el-form
        label-position="right"
        label-width="80px"
        ref="addSectionForm"
        :model="addSectionForm"
      >
        <el-form-item label="课程名称" prop="course_name">
          <el-input v-model="addSectionForm.course_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="section_name">
          <el-input v-model="addSectionForm.section_name"></el-input>
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input
            type="textarea"
            v-model="addSectionForm.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="章节排序" prop="order_num">
          <el-input v-model="addSectionForm.order_num" type="number">
            <template slot="append">数字控制排序，数字越大越靠后</template>
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddSection = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSection">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { axios } from "@/utils";
export default {
  data: function () {
    const treeProps = {
      label: (item) => {
        return item.section_name || item.theme;
      },
      children: "lessonList",
    };
    return {
      loading: false,
      contentPageTitle: "",
      showAddSection: false, // 是否显示添加修改章节的对话框
      courseId: 0,
      addSectionForm: {
        course_id: "",
        course_name: "",
        section_name: "",
        description: "",
        order_num: 0,
      },
      status:0,
      sections: [],
      treeProps,
      showStatusForm: false,
      statusForm: {
        status: 0,
      },
      statusMapping: {
        0: "已隐藏",
        1: "待更新",
        2: "已更新",
      },
    };
  },
  created() {
    this.$breadcrumbs = [
      {name:"Course",text:'课程管理'},
      {text:'内容管理'}
    ]
    console.log("课程Id=", this.$route.params.courseId);
    // const id = this.$route.params.courseId;
    this.courseId = this.$route.params.courseId;
    if (!this.courseId) {
      return this.redirectToError();
    }
    // 加载章节与课程信息(也就是树结果数据)
    this.loadChildren(this.courseId);

    // 加载课程信息
    this.loadCourse(this.courseId);
  },
  methods: {
    // 加载课程信息
    loadCourse(id) {
      this.loading = true;
      axios
        .get("/courseContent", {
          params: {
            methodName: "findCourseById",
            course_id: id,
          },
        })
        .then((res) => {
          console.log("加载课程信息：", res);
          const courseName = res.data.course_name;
          const courseId = res.data.id;
          console.log("res",res);
          // 设置课程标题
          this.contentPageTitle = courseName;
          this.addSectionForm.course_name = courseName;
          this.addSectionForm.course_id = courseId;
          this.loading = false;
        })
        .catch(() => {
          this.$message.error("加载课程信息失败");
        });
    },
    // 跳转到错误的页面
    redirectToError() {
      this.$router.replace({ path: "/not-found" });
    },
    // 确定添加章节的表单
    handleAddSection() {
      this.loading = true;
      axios
        .post("/courseContent", {
          methodName: "saveOrUpdateSection",
          section: this.addSectionForm,
        })
        .then((res) => {
          this.loading = false;
          //   console.log("添加章节返回的结果：", res);
          this.showAddSection = false;
          this.addSectionForm.section_name = "";
          this.addSectionForm.description = "";
          this.addSectionForm.order_num = 0;
          return this.loadChildren(this.courseId);
        })
        .catch(() => {
          this.loading = false;
          this.$message.error("添加章节操作失败！！");
        });
    },
    // 点击添加章节的按钮
    handleShowAddSection() {
      this.showAddSection = true;
    },
    // 加载章节树信息
    loadChildren(id) {
      this.loading = true;
      axios
        .get("/courseContent", {
          params: {
            methodName: "findSectionAndLessonByCourseId",
            course_id: id,
          },
        })
        .then((res) => {
          this.loading = false;
          console.log("加载章节树信息：", res);
          this.sections = res.data;

        })
        .catch(() => {
          this.loading = false;
          this.$message.error("请求章节树信息失败！！");
        });
    },
    handleEditSection(data) {
      console.log("编辑章节data:", JSON.parse(JSON.stringify(data)));
      Object.assign(this.addSectionForm, data);
      this.showAddSection = true;
    },
    showStatus(data) {
      console.log("节点状态的数据：", JSON.parse(JSON.stringify(data)));
      console.log("statusForm=",this.statusForm);
      this.statusForm.id = data.id;
      this.statusForm.status = data.status.toString();
      this.statusForm.data = data;
      this.showStatusForm = true;
    },
    updateStatus() {
      axios
        .get("/courseContent", {
          params: {
            methodName: "updateSectionStatus",
            status: this.statusForm.status,
            id: this.statusForm.id,
          },
        })
        .then((res) => {
          // todo 列表中显示出来的状态要同步更新
           this.statusForm.status=res.config.params.status
            this.statusForm.data.status=res.config.params.status
            this.status=res.config.params.status
          console.log("更新状态",JSON.parse(JSON.stringify(res)));
          this.statusForm = {status:"",};
          this.showStatusForm = false;
        })
        .catch((error) => {
          this.showStatusForm = false;
          this.$message.error("状态修改失败");
        });
    },
  },
};
</script>

<style>
.course-tasks .header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.course-tasks .el-tree {
  margin-top: 20px;
}

.course-tasks .el-tree,
.course-tasks .el-tree__empty-block {
  min-height: 200px;
}

.course-tasks .el-tree-node__content {
  height: auto;
}

.course-tasks .inner {
  display: flex;
  flex: 1 0 0;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
.course-tasks .actions {
  margin-left: auto;
}
</style>